package form

import (
	"context"
	"git.mycaigou.com/gfyx/common/tenant_db"
	"gorm.io/gorm"
)

type formRepo struct {
	tenant_db.TenantDB
}

func NewFormRepo() FormRepoIface {
	return &formRepo{}
}

// GetFormGroupList 获取分组列表
func (r *formRepo) GetFormGroupList(ctx context.Context, templateId string) ([]*FormGroupPo, error) {
	formGroupList := make([]*FormGroupPo, 0)
	err := r.GetTenantDB(ctx).
		Where("form_template_id=? and is_deleted=0", templateId).
		Order("sort ASC").
		Find(&formGroupList).
		Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}
	return formGroupList, nil
}

// GetFormFieldList 获取模板字段列表
func (r *formRepo) GetFormFieldList(ctx context.Context, condition map[string]interface{}) ([]*FormPo, error) {
	formFiledList := make([]*FormPo, 0)
	err := r.GetTenantDB(ctx).
		Where(condition).
		Order("sort ASC").Find(&formFiledList).
		Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

	return formFiledList, nil
}

// GetFormDataRuleList 获取数据规则
func (r *formRepo) GetFormDataRuleList(ctx context.Context, uids []string) ([]*FormDataRulePo, error) {
	formDataRulePo := make([]*FormDataRulePo, 0)
	query := r.GetTenantDB(ctx)
	if uids != nil {
		err := query.Where("uid in (?) and is_deleted=0", uids).
			Find(&formDataRulePo).
			Error
		if err != nil && err != gorm.ErrRecordNotFound {
			return nil, err
		}
	} else {
		err := query.Where("is_deleted=0").
			Find(&formDataRulePo).
			Error
		if err != nil && err != gorm.ErrRecordNotFound {
			return nil, err
		}
	}

	return formDataRulePo, nil
}
